<template>
  <div class="device-management">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="24" :sm="12" :md="6">
        <div class="stat-card online">
          <div class="stat-icon">
            <el-icon size="28" color="#67C23A"><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ onlineCount }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="stat-card offline">
          <div class="stat-icon">
            <el-icon size="28" color="#909399"><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ offlineCount }}</div>
            <div class="stat-label">离线设备</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="stat-card fault">
          <div class="stat-icon">
            <el-icon size="28" color="#F56C6C"><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ faultCount }}</div>
            <div class="stat-label">故障设备</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon size="28" color="#409EFF"><DataAnalysis /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalCount }}</div>
            <div class="stat-label">设备总数</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="page-title">
              <el-icon size="24" color="#409EFF"><Monitor /></el-icon>
              设备管理
            </h2>
            <p class="page-subtitle">管理和监控所有设备状态</p>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleAdd" class="add-button">
              <el-icon><Plus /></el-icon>
              <span class="button-text">新增设备</span>
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" :inline="true" class="search-form" ref="searchFormRef">
          <el-row :gutter="20">
            <el-col :span="24" :md="8">
              <el-form-item label="设备名称" class="form-item">
                <el-input 
                  v-model="searchForm.deviceName" 
                  placeholder="请输入设备名称" 
                  clearable 
                  class="search-input"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="8">
              <el-form-item label="设备状态" class="form-item">
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="search-select">
                  <el-option label="在线" :value="1" />
                  <el-option label="离线" :value="2" />
                  <el-option label="故障" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="8">
              <div class="search-buttons">
                <el-button type="primary" @click="handleSearch" class="search-btn">
                  <el-icon><Search /></el-icon>
                  <span class="button-text">查询</span>
                </el-button>
                <el-button @click="handleReset" class="reset-btn">
                  <el-icon><Refresh /></el-icon>
                  <span class="button-text">重置</span>
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading" 
          class="device-table"
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="deviceCode" label="设备ID" width="140">
            <template #default="scope">
              <div class="device-id">
                <el-icon><Monitor /></el-icon>
                <span>{{ scope.row.deviceCode || scope.row.deviceId }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="deviceName" label="设备名称" width="220">
            <template #default="scope">
              <div class="device-name">
                <div class="name-text">{{ scope.row.deviceName }}</div>
                <div class="device-type">{{ scope.row.deviceType }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="installLocation" label="安装位置" width="240">
            <template #default="scope">
              <div class="location-info">
                <el-icon><Location /></el-icon>
                <span>{{ scope.row.installLocation }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <div class="status-container">
                <el-tag :type="getStatusType(scope.row.status)" class="status-tag">
                  <el-icon class="status-icon">
                    <component :is="getStatusIcon(scope.row.status)" />
                  </el-icon>
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
                <div class="status-indicator" :class="getStatusClass(scope.row.status)"></div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="updateTime" label="最后更新" width="160">
            <template #default="scope">
              <div class="update-time">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(scope.row.updateTime) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button-group class="action-group">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button size="small" @click="handleView(scope.row)" class="action-btn view-btn">
                      <el-icon><View /></el-icon>
                      <span class="btn-text">查看</span>
                    </el-button>
                  </el-tooltip>
                  
                  <el-tooltip content="编辑设备" placement="top">
                    <el-button size="small" @click="handleEdit(scope.row)" class="action-btn edit-btn">
                      <el-icon><Edit /></el-icon>
                      <span class="btn-text">编辑</span>
                    </el-button>
                  </el-tooltip>
                  
                  <el-tooltip :content="scope.row.status === 2 ? '启用设备' : '禁用设备'" placement="top">
                    <el-button 
                      size="small" 
                      @click="handleToggleEnable(scope.row)" 
                      :class="['action-btn', scope.row.status === 2 ? 'enable-btn' : 'disable-btn']"
                    >
                      <el-icon>
                        <component :is="scope.row.status === 2 ? 'VideoPlay' : 'VideoPause'" />
                      </el-icon>
                      <span class="btn-text">{{ scope.row.status === 2 ? '启用' : '禁用' }}</span>
                    </el-button>
                  </el-tooltip>
                  
                  <el-tooltip content="删除设备" placement="top">
                    <el-button size="small" @click="handleDelete(scope.row)" class="action-btn delete-btn">
                      <el-icon><Delete /></el-icon>
                      <span class="btn-text">删除</span>
                    </el-button>
                  </el-tooltip>
                </el-button-group>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 新增设备弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增设备"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="addForm.deviceCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="addForm.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="addForm.deviceType" placeholder="请选择设备类型" style="width: 100%">
                <el-option
                  v-for="option in deviceTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="addForm.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="安装位置" prop="installLocation">
          <el-input v-model="addForm.installLocation" placeholder="请输入安装位置" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input-number v-model="addForm.longitude" :precision="6" placeholder="经度" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input-number v-model="addForm.latitude" :precision="6" placeholder="纬度" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input v-model="addForm.responsiblePerson" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="addForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio :value="1">在线</el-radio>
            <el-radio :value="2">离线</el-radio>
            <el-radio :value="3">故障</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAddCancel">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑设备弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑设备"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="editForm.deviceCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="editForm.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="editForm.deviceType" placeholder="请选择设备类型" style="width: 100%">
                <el-option
                  v-for="option in deviceTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="editForm.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="安装位置" prop="installLocation">
          <el-input v-model="editForm.installLocation" placeholder="请输入安装位置" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input-number v-model="editForm.longitude" :precision="6" placeholder="经度" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input-number v-model="editForm.latitude" :precision="6" placeholder="纬度" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input v-model="editForm.responsiblePerson" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :value="1">在线</el-radio>
            <el-radio :value="2">离线</el-radio>
            <el-radio :value="3">故障</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditCancel">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备详情弹窗 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="设备详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="viewDeviceData.deviceId" class="device-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备ID">{{ viewDeviceData.deviceId }}</el-descriptions-item>
          <el-descriptions-item label="设备编码">{{ viewDeviceData.deviceCode }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ viewDeviceData.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ viewDeviceData.deviceType }}</el-descriptions-item>
          <el-descriptions-item label="制造商">{{ viewDeviceData.manufacturer }}</el-descriptions-item>
          <el-descriptions-item label="安装位置">{{ viewDeviceData.installLocation }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{ viewDeviceData.longitude }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ viewDeviceData.latitude }}</el-descriptions-item>
          <el-descriptions-item label="设备状态">
            <el-tag :type="getStatusType(viewDeviceData.status)">
              {{ getStatusText(viewDeviceData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ viewDeviceData.responsiblePerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ viewDeviceData.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="安装时间">{{ formatTime(viewDeviceData.installTime) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(viewDeviceData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(viewDeviceData.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Refresh, 
  ArrowDown,
  Monitor,
  Warning,
  DataAnalysis,
  Location,
  Clock,
  View,
  Edit,
  Delete,
  VideoPlay,
  VideoPause
} from '@element-plus/icons-vue'
import { deviceApi, deviceStatusApi } from '@/servers/device'

// 响应式断点
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 获取列宽
const getColumnWidth = (column) => {
  if (isMobile.value) {
    const mobileWidths = {
      id: 100,
      deviceName: 120,
      location: 140,
      status: 100,
      lastUpdate: 140,
      actions: 200
    }
    return mobileWidths[column] || 100
  }
  const desktopWidths = {
    id: 150,
    deviceName: 250,
    location: 300,
    status: 120,
    lastUpdate: 180,
    actions: 280
  }
  return desktopWidths[column] || 150
}

// 搜索表单
const searchForm = reactive({
  deviceName: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const statsData = ref({
  onlineCount: 0,
  offlineCount: 0,
  faultCount: 0,
  totalCount: 0
})

// 计算统计数据
const onlineCount = computed(() => statsData.value.onlineCount)
const offlineCount = computed(() => statsData.value.offlineCount)
const faultCount = computed(() => statsData.value.faultCount)
const totalCount = computed(() => statsData.value.totalCount)

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    1: 'success',  // 在线
    2: 'info',     // 离线
    3: 'danger'    // 故障
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '在线',
    2: '离线',
    3: '故障'
  }
  return statusMap[status] || '未知'
}

const getStatusIcon = (status) => {
  const iconMap = {
    1: 'CircleCheck',
    2: 'CircleClose',
    3: 'Warning'
  }
  return iconMap[status] || 'QuestionFilled'
}

const getStatusClass = (status) => {
  const classMap = {
    1: 'online',
    2: 'offline',
    3: 'fault'
  }
  return classMap[status] || 'offline'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 表格行样式
const getRowClassName = ({ row, rowIndex }) => {
  if (row.status === 1) return 'row-online'
  if (row.status === 2) return 'row-offline'
  if (row.status === 3) return 'row-fault'
  return ''
}

// 获取设备列表
const fetchDeviceList = async () => {
  try {
  loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.deviceName,
      status: searchForm.status ? parseInt(searchForm.status) : undefined
    }
    
    console.log('发送请求参数:', params)
    const response = await deviceApi.getDeviceList(params)
    console.log('API响应:', response)
    
    if (response.code === 200) {
      // 后端返回的数据结构是 {code: 200, msg: '成功', obj: {...}}
      // 需要从 obj 字段中获取实际数据
      const data = response.obj || response.data || {}
      tableData.value = data.records || data.list || []
      total.value = data.total || 0
      
      console.log('设备列表数据:', tableData.value)
      console.log('总数:', total.value)
      console.log('原始响应数据结构:', response)
      
      // 计算统计数据
      calculateStats()
    } else {
      console.error('API返回错误:', response)
      ElMessage.error(`获取设备列表失败: ${response.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error(`获取设备列表失败: ${error.message || '网络连接失败'}`)
    
    // 如果是网络错误，显示更详细的信息
    if (error.message && error.message.includes('Network Error')) {
      ElMessage.error('无法连接到后端服务，请检查后端是否在8891端口启动')
    }
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = () => {
  const stats = {
    onlineCount: 0,
    offlineCount: 0,
    faultCount: 0,
    totalCount: 0
  }
  
  tableData.value.forEach(device => {
    stats.totalCount++
    switch (device.status) {
      case 1:
        stats.onlineCount++
        break
      case 2:
        stats.offlineCount++
        break
      case 3:
        stats.faultCount++
        break
    }
  })
  
  statsData.value = stats
}

// 操作方法
const handleSearch = () => {
  currentPage.value = 1
  fetchDeviceList()
}

const handleReset = () => {
  searchForm.deviceName = ''
  searchForm.status = ''
  currentPage.value = 1
  fetchDeviceList()
}



// 新增设备弹窗相关
const addDialogVisible = ref(false)
const addForm = ref({
  deviceCode: '',
  deviceName: '',
  deviceType: '',
  manufacturer: '',
  installLocation: '',
  longitude: null,
  latitude: null,
  status: 1,
  responsiblePerson: '',
  contactPhone: ''
})

const addFormRef = ref(null)
const addLoading = ref(false)

// 设备类型选项
const deviceTypeOptions = [
  { label: '水质监测', value: '水质监测' },
  { label: '流量监测', value: '流量监测' },
  { label: '压力监测', value: '压力监测' },
  { label: '温度监测', value: '温度监测' },
  { label: '液位监测', value: '液位监测' },
  { label: 'pH监测', value: 'pH监测' },
  { label: '溶解氧监测', value: '溶解氧监测' }
]

// 表单验证规则
const formRules = {
  deviceCode: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
    { min: 2, max: 50, message: '设备编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 100, message: '设备名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  manufacturer: [
    { required: true, message: '请输入制造商', trigger: 'blur' },
    { min: 2, max: 100, message: '制造商名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  installLocation: [
    { required: true, message: '请输入安装位置', trigger: 'blur' },
    { min: 2, max: 200, message: '安装位置长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  responsiblePerson: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 2, max: 50, message: '负责人姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ]
}

const handleAdd = () => {
  // 重置表单
  addForm.value = {
    deviceCode: '',
    deviceName: '',
    deviceType: '',
    manufacturer: '',
    installLocation: '',
    longitude: null,
    latitude: null,
    status: 1,
    responsiblePerson: '',
    contactPhone: ''
  }
  addDialogVisible.value = true
}

// 提交新增设备
const handleAddSubmit = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    const response = await deviceApi.addDevice(addForm.value)
    
    if (response.code === 200) {
      ElMessage.success('设备新增成功')
      addDialogVisible.value = false
      // 刷新设备列表
      await fetchDeviceList()
    } else {
      ElMessage.error(`新增失败: ${response.msg}`)
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      console.error('新增设备失败:', error)
      ElMessage.error(`新增设备失败: ${error.message || '未知错误'}`)
    }
  } finally {
    addLoading.value = false
  }
}

// 取消新增
const handleAddCancel = () => {
  addDialogVisible.value = false
}

// 设备详情弹窗相关
const viewDialogVisible = ref(false)
const viewDeviceData = ref({})

const handleView = async (row) => {
  try {
    const response = await deviceApi.getDeviceDetail(row.deviceId)
    if (response.code === 200) {
      const data = response.obj || response.data || {}
      viewDeviceData.value = data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(`获取设备详情失败: ${response.msg}`)
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    ElMessage.error(`获取设备详情失败: ${error.message || '未知错误'}`)
  }
}

// 编辑设备弹窗相关
const editDialogVisible = ref(false)
const editForm = ref({})
const editFormRef = ref(null)
const editLoading = ref(false)

const handleEdit = async (row) => {
  try {
    const response = await deviceApi.getDeviceDetail(row.deviceId)
    if (response.code === 200) {
      const data = response.obj || response.data || {}
      editForm.value = { ...data }
      editDialogVisible.value = true
    } else {
      ElMessage.error(`获取设备信息失败: ${response.msg}`)
    }
  } catch (error) {
    console.error('获取设备信息失败:', error)
    ElMessage.error(`获取设备信息失败: ${error.message || '未知错误'}`)
  }
}

// 提交编辑设备
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    const response = await deviceApi.updateDevice(editForm.value)
    
    if (response.code === 200) {
      ElMessage.success('设备更新成功')
      editDialogVisible.value = false
      // 刷新设备列表
      await fetchDeviceList()
    } else {
      ElMessage.error(`更新失败: ${response.msg}`)
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      console.error('更新设备失败:', error)
      ElMessage.error(`更新设备失败: ${error.message || '未知错误'}`)
    }
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleEditCancel = () => {
  editDialogVisible.value = false
}

const handleToggleEnable = async (row) => {
  const action = row.status === 2 ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm(
    `确定要${action}设备 "${row.deviceName}" 吗？`, 
    `${action}设备`, 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
        type: row.status === 2 ? 'success' : 'warning'
      }
    )
    
    // 更新设备状态
    const updateData = {
      deviceId: row.deviceId,
      status: row.status === 2 ? 1 : 2 // 启用设为在线，禁用设为离线
    }
    
    const response = await deviceApi.updateDevice(updateData)
    if (response.code === 200) {
      row.status = updateData.status
      row.updateTime = new Date()
      ElMessage.success(`设备 "${row.deviceName}" ${action}成功`)
      calculateStats()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}设备失败:`, error)
      ElMessage.error(`${action}设备失败`)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备 "${row.deviceName}" 吗？`, 
      '删除设备', 
      {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
      }
    )
    
    const response = await deviceApi.deleteDevice(row.deviceId)
    if (response.code === 200) {
    ElMessage.success('删除成功')
      // 刷新设备列表
      await fetchDeviceList()
    } else {
      ElMessage.error(`删除失败: ${response.msg}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除设备失败:', error)
      ElMessage.error(`删除设备失败: ${error.message || '未知错误'}`)
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchDeviceList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDeviceList()
}

onMounted(() => {
  fetchDeviceList()
})
</script>

<style scoped>
.device-management {
  padding: 0;
  background: transparent;
  min-height: calc(100vh - 120px);
  width: 100%;
  max-width: 100%;
}

/* 统计卡片样式 */
.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  background: #ffffff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  transition: all 0.3s ease;
}

.stat-card.online::before {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-card.offline::before {
  background: linear-gradient(135deg, #909399, #B1B3B8);
}

.stat-card.fault::before {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stat-card.total::before {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  margin-right: 16px;
  padding: 12px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-card.online .stat-icon {
  background: rgba(103, 194, 58, 0.1);
}

.stat-card.offline .stat-icon {
  background: rgba(144, 147, 153, 0.1);
}

.stat-card.fault .stat-icon {
  background: rgba(245, 108, 108, 0.1);
}

.stat-card.total .stat-icon {
  background: rgba(64, 158, 255, 0.1);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #333333;
  margin-bottom: 4px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 主卡片样式 */
.main-card {
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  overflow: hidden;
  width: 100%;
  max-width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #ebeef5;
  flex-wrap: wrap;
  gap: 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
  color: #333333;
  margin: 0 0 8px 0;
  gap: 12px;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
  font-weight: 400;
}

.header-right {
  display: flex;
  align-items: center;
}

.add-button {
  border-radius: 8px;
  padding: 12px 20px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 搜索区域样式 */
.search-section {
  padding: 24px 20px;
  background: #fafbfc;
  border-bottom: 1px solid #ebeef5;
}

.search-form {
  background: #ffffff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #ebeef5;
}

.form-item {
  width: 100%;
  margin-bottom: 0;
}

.search-input,
.search-select {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.search-select :deep(.el-select__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
  height: 100%;
}

.search-btn,
.reset-btn {
  border-radius: 8px;
  padding: 10px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-btn {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.reset-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 表格区域样式 */
.table-section {
  padding: 0 20px;
  width: 100%;
  overflow-x: auto;
}

.device-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid #ebeef5;
  width: 100%;
  min-width: 1080px;
}

/* 表格单元格样式 */
.device-id {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  color: #409EFF;
  font-size: 13px;
}

.device-id span {
  word-break: break-all;
}

.device-name {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.name-text {
  font-weight: 600;
  color: #333333;
  font-size: 13px;
  line-height: 1.3;
  word-break: break-all;
}

.device-type {
  font-size: 11px;
  color: #909399;
  background: #f5f7fa;
  padding: 1px 6px;
  border-radius: 10px;
  display: inline-block;
  width: fit-content;
  margin-top: 2px;
}

.location-info {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
}

.location-info span {
  word-break: break-all;
  flex: 1;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  border-radius: 20px;
  padding: 6px 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status-icon {
  font-size: 12px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-indicator.online {
  background: #67C23A;
}

.status-indicator.offline {
  background: #909399;
}

.status-indicator.fault {
  background: #F56C6C;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.update-time {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 12px;
  line-height: 1.3;
}

.update-time span {
  word-break: break-all;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

.action-group {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.action-btn {
  border: none;
  border-radius: 0;
  padding: 6px 8px;
  height: 32px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.action-btn:hover::before {
  left: 100%;
}

.view-btn {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
  color: white;
}

.view-btn:hover {
  background: linear-gradient(135deg, #337ECC, #5A9FE8);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.edit-btn {
  background: linear-gradient(135deg, #67C23A, #85CE61);
  color: white;
}

.edit-btn:hover {
  background: linear-gradient(135deg, #5DA934, #73B84D);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
}

.delete-btn {
  background: linear-gradient(135deg, #F56C6C, #F78989);
  color: white;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #E55A5A, #F67A7A);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.4);
}

.enable-btn {
  background: linear-gradient(135deg, #67C23A, #85CE61);
  color: white;
}

.enable-btn:hover {
  background: linear-gradient(135deg, #5DA934, #73B84D);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
}

.disable-btn {
  background: linear-gradient(135deg, #E6A23C, #F0C78A);
  color: white;
}

.disable-btn:hover {
  background: linear-gradient(135deg, #D4942E, #E8B574);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(230, 162, 60, 0.4);
}

.btn-text {
  font-size: 12px;
  font-weight: 500;
}

/* 按钮组之间的分隔线 */
.action-btn:not(:last-child) {
  border-right: 1px solid rgba(255, 255, 255, 0.2);
}

/* 分页样式 */
.pagination-section {
  padding: 20px 20px;
  background: #fafbfc;
  border-top: 1px solid #ebeef5;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  gap: 10px;
}

/* 表格行样式 */
:deep(.el-table .row-online) {
  background: rgba(103, 194, 58, 0.02);
}

:deep(.el-table .row-offline) {
  background: rgba(144, 147, 153, 0.02);
}

:deep(.el-table .row-fault) {
  background: rgba(245, 108, 108, 0.02);
}

:deep(.el-table tr:hover td) {
  background: #f0f9ff !important;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #ebeef5;
  padding: 12px 8px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f5f7fa;
  padding: 12px 8px;
}

/* 强制表格撑满宽度 */
:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
}

:deep(.el-table__header-wrapper) {
  width: 100% !important;
}

/* 按钮文本 */
.button-text {
  margin-left: 6px;
}

/* 大屏幕优化 */
@media (min-width: 1400px) {
  .device-table {
    min-width: 100%;
  }
  
  :deep(.el-table th) {
    padding: 20px 16px;
  }
  
  :deep(.el-table td) {
    padding: 20px 16px;
  }
}

@media (min-width: 1600px) {
  .device-table {
    min-width: 100%;
  }
  
  :deep(.el-table th) {
    padding: 24px 20px;
  }
  
  :deep(.el-table td) {
    padding: 24px 20px;
  }
}

@media (min-width: 1920px) {
  .table-section {
    padding: 0 40px;
  }
  
  .card-header {
    padding: 24px 40px;
  }
  
  .search-section {
    padding: 24px 40px;
  }
  
  .pagination-section {
    padding: 20px 40px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-row {
    margin-bottom: 16px;
  }
  
  .stat-card {
    padding: 16px;
    margin-bottom: 12px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .stat-label {
    font-size: 13px;
  }
  
  .card-header {
    padding: 16px 20px;
    flex-direction: column;
    align-items: stretch;
  }
  
  .page-title {
    font-size: 20px;
    margin-bottom: 6px;
  }
  
  .page-subtitle {
    font-size: 13px;
  }
  
  .search-section {
    padding: 16px 20px;
  }
  
  .search-form {
    padding: 16px;
  }
  
  .table-section {
    padding: 0 16px;
  }
  
  .pagination-section {
    padding: 16px 16px;
  }
  
  .button-text {
    display: none;
  }
  
  .action-group {
    flex-direction: column;
    width: 100%;
  }
  
  .action-btn {
    width: 100%;
    border-radius: 6px;
    margin: 2px 0;
    border-right: none !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  }
  
  .action-btn:last-child {
    border-bottom: none;
  }
  
  .btn-text {
    font-size: 12px;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th) {
    padding: 12px 8px;
  }
  
  :deep(.el-table td) {
    padding: 12px 8px;
  }
}

@media (max-width: 480px) {
  .stat-card {
    padding: 12px;
  }
  
  .stat-icon {
    margin-right: 12px;
    padding: 8px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .stat-label {
    font-size: 12px;
  }
  
  .card-header {
    padding: 12px 16px;
  }
  
  .page-title {
    font-size: 18px;
  }
  
  .search-section {
    padding: 12px 12px;
  }
  
  .search-form {
    padding: 12px;
  }
  
  .table-section {
    padding: 0 12px;
  }
  
  .pagination-section {
    padding: 12px 12px;
  }
  
  :deep(.el-table th) {
    padding: 8px 4px;
    font-size: 11px;
  }
  
  :deep(.el-table td) {
    padding: 8px 4px;
    font-size: 10px;
  }
  
  .device-name {
    gap: 2px;
  }
  
  .name-text {
    font-size: 12px;
  }
  
  .device-type {
    font-size: 10px;
    padding: 1px 6px;
  }
}

/* 弹窗样式 */
.dialog-footer {
  text-align: right;
}

.device-detail {
  padding: 20px 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>